<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */

namespace App\Strategy;

use App\Service\BinanceService;

class MaCrossoverStrategy
{
    protected BinanceService $binance;

    // 设置短期和长期均线的周期
    protected int $shortPeriod = 5;

    protected int $longPeriod = 20;

    public function __construct(BinanceService $binance)
    {
        $this->binance = $binance;
    }

    /**
     * 判断是否需要买入或卖出.
     */
    public function handle(string $symbol): array
    {
        $symbol = strtoupper($symbol);

        // 获取 K 线数据
        $klines = $this->binance->getKlines($symbol, '1m', $this->longPeriod + 1);

        // 如果数据不足，返回不操作
        if (count($klines) < $this->longPeriod) {
            return ['action' => 'none', 'reason' => '数据不足'];
        }

        // 提取收盘价
        $closes = array_column($klines, 4);

        // 计算短期和长期均线
        $shortMa = array_sum(array_slice($closes, -$this->shortPeriod)) / $this->shortPeriod;
        $longMa = array_sum(array_slice($closes, -$this->longPeriod)) / $this->longPeriod;

        // 获取上一轮的均线数据（用于判断交叉）
        $lastShortMa = array_sum(array_slice($closes, -$this->shortPeriod - 1, $this->shortPeriod)) / $this->shortPeriod;
        $lastLongMa = array_sum(array_slice($closes, -$this->longPeriod - 1, $this->longPeriod)) / $this->longPeriod;

        // 判断买入信号：短期均线从下向上穿过长期均线
        if ($lastShortMa < $lastLongMa && $shortMa > $longMa) {
            return ['action' => 'buy', 'price' => end($closes)];
        }

        // 判断卖出信号：短期均线从上向下穿过长期均线
        if ($lastShortMa > $lastLongMa && $shortMa < $longMa) {
            return ['action' => 'sell', 'price' => end($closes)];
        }

        // 如果没有交叉，不做操作
        return ['action' => 'none'];
    }
}
